package com.androidbook.btdt_week9;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.Vector;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.location.Address;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore.Images.Media;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class QuizSettingsActivity extends QuizActivity {
    SharedPreferences mGameSettings;
    List<GPSCoords> mFavPlaceCoords;
    View dialogLayout;
    View questionSuggestLayout;
    String strSuggestImageUri;
    int selectItem;
    Context cxt;
    FriendRequestTask friendRequest;
    
    static final int DATE_DIALOG_ID = 0;
    static final int PASSWORD_DIALOG_ID = 1;
    static final int PLACE_DIALOG_ID = 2;
    static final int SUGGEST_DIALOG_ID = 3;
    static final int FRIEND_EMAIL_DIALOG_ID = 4;
    static final int EMAIL_DROID_DIALOG_ID = 5;
    
    static final int TAKE_AVATAR_CAMERA_REQUEST = 1;
    static final int TAKE_AVATAR_GALLERY_REQUEST = 2;
    static final int TAKE_AVATAR_SUGGEST_REQUEST = 3;
    
    static final String DROID_ADD_ACTION = "add";
    static final String DROID_REMOVE_ACTION = "remove";
    static final String DROID_FIND_ACTION = "find"; 
    static final String DROID_ADD_TAG = "<added>";
    static final String DROID_REMOVE_TAG = "<removed>";
    static final String DROID_FIND_TAG = "<found>";

    
    private void doFriendRequest(String friendEmail, String action, String tagResult) {
    	// make sure we don't collide with another pending update
    	if (friendRequest == null || friendRequest.getStatus() == AsyncTask.Status.FINISHED || friendRequest.isCancelled()) {
    		friendRequest = new FriendRequestTask();
    		friendRequest.execute(friendEmail, action, tagResult);
    	} else {
    	   	Log.w(TAG, "Warning: friendRequestTask already going");
    	}
    }
    
    /**
     * 
     * @param view
     *            the button
     */
    public void onAddFriendButtonClick(View view) {
    	showDialog(FRIEND_EMAIL_DIALOG_ID);
    }
    
    /**
     * 
     * @param view
     *            the button
     */
    public void onRemoveFriendButtonClick(View view) {
    	showDialog(FRIEND_EMAIL_DIALOG_ID);
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
        
        cxt = QuizSettingsActivity.this;
        
        // Retrieve the shared preferences
        mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);

        // Initialize the avatar button
        initAvatar();
        
        // Initialize the nickname entry
        initNicknameEntry();

        // Initialize the email entry
        initEmailEntry();
        
        // Initialize the Password chooser
        initPasswordChooser();
        
        // Initialize the Date picker
        initDatePicker();
        
        // Initialize the spinner
        initGenderSpinner();
        
        Log.d(TAG, "antes de initfavoriteplacepicker");
        // Initialize the favorite place picker
        initFavoritePlacePicker();
        Log.d(TAG, "despues de initfavoriteplacepicker");
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        
        getMenuInflater().inflate(R.menu.settingsoptions, menu);
        getMenuInflater().inflate(R.menu.droid_add_menu, menu);
		getMenuInflater().inflate(R.menu.droid_remove_menu, menu);
		
        Log.d(TAG, "onCreateOptionsMenu");
     //   menu.findItem(R.id.help_menu_item).setIntent(new Intent(this, QuizHelpActivity.class));
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        Log.d(TAG, "onOptionsItemSelected");
        
        Bundle params = new Bundle(); 
        if(item.getTitle().equals(getResources().getString(R.string.droid_add_settings))) {
	        params.putString("action", DROID_ADD_ACTION);
	        params.putString("tag_result", DROID_ADD_TAG);
	        showDialog(EMAIL_DROID_DIALOG_ID, params);
        }else if(item.getTitle().equals(getResources().getString(R.string.droid_remove_settings))) {
	        params.putString("action", DROID_REMOVE_ACTION);
	        params.putString("tag_result", DROID_REMOVE_TAG);
	        showDialog(EMAIL_DROID_DIALOG_ID, params);
        } else {
        	showDialog(SUGGEST_DIALOG_ID);
        }
        
        Log.d(TAG, "onOptionsItemSelected, end");
        return true;
    }
    
    @Override
	protected Dialog onCreateDialog(int id) {
	    switch (id) {
	    	case PLACE_DIALOG_ID:
	    		Log.d(TAG, "empieza place dialog");
	            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(
	            		Context.LAYOUT_INFLATER_SERVICE);
	            dialogLayout = layoutInflater.inflate(R.layout.fav_place_dialog, 
	            		(ViewGroup) findViewById(R.id.root));
	            
	            final TextView placeCoordinates = (TextView) dialogLayout.findViewById(
	            		R.id.TextView_FavPlaceCoords_Info);
	            final EditText placeName = (EditText) dialogLayout.findViewById(
	            		R.id.EditText_FavPlaceName);
	            placeName.setOnKeyListener(new View.OnKeyListener() {
	
	                public boolean onKey(View v, int keyCode, KeyEvent event) {
	                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
	
	                        String strPlaceName = placeName.getText().toString();
	                        if ((strPlaceName != null) && (strPlaceName.length() > 0)) {
	                            // Try to resolve string into GPS coords
	                            resolveLocation(strPlaceName);
	                            
//	                            Editor editor = mGameSettings.edit();
//	                            Log.d(TAG, "place_name (onkey - placename) = " + mFavPlaceCoords.get(selectItem).name_place);
//	                            editor.putString(GAME_PREFERENCES_FAV_PLACE_NAME, mFavPlaceCoords.get(selectItem).name_place);
//	                            Log.d(TAG, "place_name (onkey - placename) = " + mFavPlaceCoords.get(selectItem).mLon);
//	                            editor.putFloat(GAME_PREFERENCES_FAV_PLACE_LONG, mFavPlaceCoords.get(selectItem).mLon);
//	                            Log.d(TAG, "place_name (onkey - placename) = " + mFavPlaceCoords.get(selectItem).mLat);
//	                            editor.putFloat(GAME_PREFERENCES_FAV_PLACE_LAT, mFavPlaceCoords.get(selectItem).mLat);
//	                            editor.commit();
	
//	                            Log.d(TAG, "Name set:" + mGameSettings.getString(GAME_PREFERENCES_FAV_PLACE_NAME, "not set"));
	                            
	                            placeCoordinates.setText(formatCoordinates(mFavPlaceCoords.get(selectItem).mLat, 
	                            		mFavPlaceCoords.get(selectItem).mLon));
	                            return true;
	                        }
	                    }
	                    return false;
	                }
	            });
	
	            Log.d(TAG, "place dialog - antes de mapbutton");
	            final Button mapButton = (Button) dialogLayout.findViewById(R.id.Button_MapIt);
	            mapButton.setOnClickListener(new View.OnClickListener() {
	                public void onClick(View v) {
	
	                    // Try to resolve string into GPS coords
//	                    String placeToFind = placeName.getText().toString();
//	                    resolveLocation(placeToFind);
	
//	                    Editor editor = mGameSettings.edit();
//	                    editor.putString(GAME_PREFERENCES_FAV_PLACE_NAME, placeToFind);
//	                    editor.putFloat(GAME_PREFERENCES_FAV_PLACE_LONG, mFavPlaceCoords.mLon);
//	                    editor.putFloat(GAME_PREFERENCES_FAV_PLACE_LAT, mFavPlaceCoords.mLat);
//	                    editor.commit();
	
	                    placeCoordinates.setText(formatCoordinates(mFavPlaceCoords.get(selectItem).mLat,
	                    		mFavPlaceCoords.get(selectItem).mLon));
	
	                    // Get the zoom
	                    EditText zoomMap = (EditText) dialogLayout.findViewById(R.id.editText_zoom);
	                    String zoomText = zoomMap.getText().toString();
	                    int zoomValue = 10;
	                    if ((zoomText != null) && (zoomText.length() > 0)) {
	                    	zoomValue = Integer.parseInt(zoomText);
	                    }
	                    if (zoomValue < 2 || zoomValue > 23 || zoomText == null) {
                        		Toast.makeText(QuizSettingsActivity.this,
                        				"El valor del zoom debe estar entre 2 y 23. Se usará por defecto el valor 10", 
                        				Toast.LENGTH_LONG).show();
                        		zoomValue = 10;
	                    }
	                    
	                    // Launch map with gps coords
	                    // String geoURI = String.format("geo:%f,%f?z=10", mFavPlaceCoords.mLat, mFavPlaceCoords.mLon);
	                    
	                    // Cambio: Locale.US para que las comas decimales sean puntos
	                    // La doc de Java String lo recomienda para las cadenas que 
	                    // no son para que las vean los humanos
	                    String temp = Integer.toString(zoomValue);
	                    Log.d(TAG, "zoom es = " + temp);
	                    String geoURI = String.format(Locale.US, "geo:%f,%f?z="+temp, 
	                    		mFavPlaceCoords.get(selectItem).mLat, mFavPlaceCoords.get(selectItem).mLon, zoomValue);
	                    Log.d(TAG, "geouri = " + geoURI);
	                    Uri geo = Uri.parse(geoURI);
	                    Intent geoMap = new Intent(Intent.ACTION_VIEW, geo);
	                    startActivity(geoMap);
	                }
	            });
	            
	            Log.d(TAG, "place dialog - antes de zoommap");
	            final EditText zoomMap = (EditText) dialogLayout.findViewById(R.id.editText_zoom);
	            zoomMap.setOnKeyListener(new View.OnKeyListener() {
	
	                public boolean onKey(View v, int keyCode, KeyEvent event) {
	                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
	
	                        String strZoomValue = zoomMap.getText().toString();
	                        if ((strZoomValue != null) && (strZoomValue.length() > 0)) {
	                            
	                        	int tempValue = Integer.parseInt(strZoomValue);
	                        	
	                        	if (tempValue < 2 || tempValue > 23) {
	                        		Toast.makeText(QuizSettingsActivity.this,"El valor del zoom debe estar entre 2 y 23",
	                        				Toast.LENGTH_LONG).show();
	                        	}
	
	                            return true;
	                        }
	                    }
	                    return false;
	                }
	            });
	
	            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
	            dialogBuilder.setView(dialogLayout);
	
	            // Now configure the AlertDialog
	            dialogBuilder.setTitle(R.string.settings_button_favoriteplace);
	
	            dialogBuilder.setNegativeButton(android.R.string.cancel, 
	            		new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int whichButton) {
	                    // We forcefully dismiss and remove the Dialog, so it cannot 
	                	// be used again (no cached info)
	                	Log.d(TAG, "dialogBuilder.setNegativeButton (antes de hacer removeDialog(PLACE_DIALOG_ID)");
	                    QuizSettingsActivity.this.removeDialog(PLACE_DIALOG_ID);
	                    Log.d(TAG, "dialogBuilder.setNegativeButton (despues de hacer removeDialog(PLACE_DIALOG_ID)");
	                }
	            });
	
	            Log.d(TAG, "place dialog - antes de positivebutton");
	            dialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	
	                    TextView placeInfo = (TextView) findViewById(R.id.TextView_FavoritePlace_Info);
	                    String strPlaceName = placeName.getText().toString();
	
	                    if ((strPlaceName != null) && (strPlaceName.length() > 0) && (selectItem != 0)) {
	                        
				        	Editor editor = mGameSettings.edit();
				        	Log.d(TAG, "name_place (onclick - positiveButton) = " + mFavPlaceCoords.get(selectItem).name_place);
	                        editor.putString(GAME_PREFERENCES_FAV_PLACE_NAME, mFavPlaceCoords.get(selectItem).name_place);                        
	                        Log.d(TAG, "lon (onclick - positiveButton) = " + mFavPlaceCoords.get(selectItem).mLon);
	                        editor.putFloat(GAME_PREFERENCES_FAV_PLACE_LONG, mFavPlaceCoords.get(selectItem).mLon);
	                        Log.d(TAG, "mlat (onclick - positiveButton) = " + mFavPlaceCoords.get(selectItem).mLat);
	                        editor.putFloat(GAME_PREFERENCES_FAV_PLACE_LAT, mFavPlaceCoords.get(selectItem).mLat);
	                        editor.commit();	
	                        
	                        Log.d(TAG, "Name set:" + mGameSettings.getString(GAME_PREFERENCES_FAV_PLACE_NAME, "not set"));
	
	                        placeInfo.setText(mFavPlaceCoords.get(selectItem).name_place);
	                    }
	
	                    // We forcefully dismiss and remove the Dialog, so it cannot be used again
	                    Log.d(TAG, "dialogBuilder.setPositiveButton (antes de hacer removeDialog(PLACE_DIALOG_ID)");
	                    QuizSettingsActivity.this.removeDialog(PLACE_DIALOG_ID);
	                    Log.d(TAG, "dialogBuilder.setPositiveButton (despues de hacer removeDialog(PLACE_DIALOG_ID)");
	                }
	            });
	
	            // Create the AlertDialog and return it
	            AlertDialog placeDialog = dialogBuilder.create();
	            
	            Log.d(TAG, "place dialog - antes de spinlocations");
	            Spinner spinLocations = (Spinner) dialogLayout.findViewById(R.id.spinner_Place);
	            spinLocations.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			        public void onItemSelected(AdapterView<?> parent, View itemSelected, 
			        		int selectedItemPosition, long selectedId) {
			            
			            ////////////////////////////////////////////////////////////////////////////
			        	Log.d(TAG, "selectedItemPosition = " + selectedItemPosition);
			        	selectItem = selectedItemPosition;
			        	
//			        	Editor editor = mGameSettings.edit();
//			        	Log.d(TAG, "name_place (setonitemselected - spinLocations) = " + mFavPlaceCoords.get(selectItem).name_place);
//                        editor.putString(GAME_PREFERENCES_FAV_PLACE_NAME, mFavPlaceCoords.get(selectItem).name_place);                        
//                        Log.d(TAG, "lon (setonitemselected - spinLocations) = " + mFavPlaceCoords.get(selectItem).mLon);
//                        editor.putFloat(GAME_PREFERENCES_FAV_PLACE_LONG, mFavPlaceCoords.get(selectItem).mLon);
//                        Log.d(TAG, "mlat (setonitemselected - spinLocations) = " + mFavPlaceCoords.get(selectItem).mLat);
//                        editor.putFloat(GAME_PREFERENCES_FAV_PLACE_LAT, mFavPlaceCoords.get(selectItem).mLat);
//                        editor.commit();	
//                        
//                        Log.d(TAG, "Name set:" + mGameSettings.getString(GAME_PREFERENCES_FAV_PLACE_NAME, "not set"));
                        
                        //Update the coords
                        placeCoordinates.setText(formatCoordinates(mFavPlaceCoords.get(selectItem).mLat,
	                    		mFavPlaceCoords.get(selectItem).mLon));
			        }
			
			        public void onNothingSelected(AdapterView<?> parent) {
			        }
			    });
	            Log.d(TAG, "place dialog - fin creacion");
	            return placeDialog;
	    
	    case DATE_DIALOG_ID:
	        final TextView dob = (TextView) findViewById(R.id.TextView_DOB_Info);
	        Calendar now = Calendar.getInstance(); 
	        
	        DatePickerDialog dateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
	            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
	                
	                Time dateOfBirth = new Time();
	                dateOfBirth.set(dayOfMonth, monthOfYear, year);
	                long dtDob = dateOfBirth.toMillis(true);
	                dob.setText(DateFormat.format("MMMM dd, yyyy", dtDob));
	                
	                Editor editor = mGameSettings.edit();
	                editor.putLong(GAME_PREFERENCES_DOB, dtDob);
	                editor.commit();
	            }
	        },  now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
	        return dateDialog;
	        
	    case PASSWORD_DIALOG_ID:
			LayoutInflater inflater = (LayoutInflater) getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			final View layout = inflater.inflate(R.layout.password_dialog, 
					(ViewGroup) findViewById(R.id.root));
			final EditText p1 = (EditText) layout.findViewById(R.id.EditText_Pwd1);
			final EditText p2 = (EditText) layout.findViewById(R.id.EditText_Pwd2);
			final TextView error = (TextView) layout.findViewById(R.id.TextView_PwdProblem);
			p2.addTextChangedListener(new TextWatcher() {
	        	@Override
	        	public void afterTextChanged(Editable s) {
	                String strPass1 = p1.getText().toString();
	                String strPass2 = p2.getText().toString();
	                if (strPass1.equals(strPass2)) {
	                	error.setTextColor(Color.GREEN);
	                    error.setText(R.string.settings_pwd_equal);
	                } else {
	                	error.setTextColor(Color.RED);
	                    error.setText(R.string.settings_pwd_not_equal);
	                }
	            }
	
	            // ... other required overrides need not be implemented 
	
	            @Override
	            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	            }
	
	            @Override
	            public void onTextChanged(CharSequence s, int start, int before, int count) {
	            }
			});
	        AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder.setView(layout);
	    
	        // Now configure the AlertDialog
	        builder.setTitle(R.string.settings_button_pwd);
	        builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	                // We forcefully dismiss and remove the Dialog, so it cannot be used again (no cached info)
	                QuizSettingsActivity.this.removeDialog(PASSWORD_DIALOG_ID);
	            }
	        });
	        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	                TextView passwordInfo = (TextView) findViewById(R.id.TextView_Password_Info);
	                String strPassword1 = p1.getText().toString();
	                String strPassword2 = p2.getText().toString();
	                if (strPassword1.equals(strPassword2)) {
	                    Editor editor = mGameSettings.edit();
	                    editor.putString(GAME_PREFERENCES_PASSWORD, strPassword1);
	                    editor.commit();
	                    passwordInfo.setText(R.string.settings_pwd_set);
	                } else {
	                    Log.d(TAG, "Passwords do not match. Not saving. Keeping old password (if set).");
	                }
	                // We forcefully dismiss and remove the Dialog, so it cannot be used again
	                QuizSettingsActivity.this.removeDialog(PASSWORD_DIALOG_ID);
	            }
	        });
	    
	        // Create the AlertDialog and return it
	        AlertDialog passwordDialog = builder.create();
	        return passwordDialog;
	        
	    case SUGGEST_DIALOG_ID:
	    	LayoutInflater inflater2 = (LayoutInflater) getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
	    	questionSuggestLayout = inflater2.inflate(R.layout.suggestions_dialog, 
					(ViewGroup) findViewById(R.id.root));
	    	
	    	ImageButton btn = (ImageButton) questionSuggestLayout.findViewById(R.id.ImageButton_Avatar_suggest);
	    	btn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.d(TAG, ">onClick elegir imagen de la pregunta");
					String strAvatarPrompt = "Choose a picture to use as image of the question!";
		            Intent pickPhoto = new Intent(Intent.ACTION_PICK);
		            Log.d(TAG, ">intent action_pick");
		            pickPhoto.setType("image/*");
		            Log.d(TAG, ">setType");
		            startActivityForResult(Intent.createChooser(pickPhoto, strAvatarPrompt),
		                    TAKE_AVATAR_SUGGEST_REQUEST);
		            Log.d(TAG, ">startActivityForResult");
				}
			    
			});	    	
	    	
	    	AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
	        builder2.setView(questionSuggestLayout);
	        
	        // Now configure the AlertDialog
	    	builder2.setTitle(R.string.menu_item_suggest_title);
	    	builder2.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	// We forcefully dismiss and remove the Dialog, so it cannot be used again (no cached info)
	                QuizSettingsActivity.this.removeDialog(SUGGEST_DIALOG_ID);
	            }
	    	});
	    	builder2.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	                // Upload data
	            	Intent uploadService = new Intent(getApplicationContext(), UploaderService.class);

	            	EditText t = (EditText) questionSuggestLayout.findViewById(R.id.question_text);
	            	String questionText = t.getText().toString();
	            	
	            	if (strSuggestImageUri != null && strSuggestImageUri.compareTo("")!=0 &&
	            			questionText != null && questionText.compareTo("")!=0) {
		            	//add extras
		            	Bundle bundle = new Bundle();
		            	bundle.putString("imageUri", strSuggestImageUri);
		            	bundle.putString("question", questionText);	            	
		            	
		            	uploadService.putExtras(bundle);
		            	uploadService.setAction(SUGGEST_SERVICE);
		            	startService(uploadService);
	            
	            		//Toast.makeText(QuizSettingsActivity.this, "Subiendo...", Toast.LENGTH_SHORT).show();
	            	}  else {
	            		Toast.makeText(QuizSettingsActivity.this, "No se subirá nada, debe indicarse" +
	            				" una pregunta y una imagen.", 
	            				Toast.LENGTH_LONG).show();
	            	}
	                // We forcefully dismiss and remove the Dialog, so it cannot be used again
	                QuizSettingsActivity.this.removeDialog(SUGGEST_DIALOG_ID);
	            }
	        });
	        // Create the AlertDialog and return it
	        AlertDialog suggestDialog = builder2.create();
	        return suggestDialog;
	        
	    case FRIEND_EMAIL_DIALOG_ID: 
	    	Log.d(TAG, "onCreateDialog-friend_email_dialog_id- 0");
	    	LayoutInflater infl = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    	final View friendDialogLayout = infl.inflate(R.layout.friend_dialog, (ViewGroup) findViewById(R.id.root));

	    	Log.d(TAG, "onCreateDialog-friend_email_dialog_id - 1");
	    	AlertDialog.Builder friendDialogBuilder = new AlertDialog.Builder(this);
	    	friendDialogBuilder.setView(friendDialogLayout);
	    	final TextView emailText = (TextView) friendDialogLayout.findViewById(R.id.EditText_Friend_Email);
	    	Log.d(TAG, "onCreateDialog-friend_email_dialog_id - 2");
	    	
	    	friendDialogBuilder.setPositiveButton(R.string.addFriend, new DialogInterface.OnClickListener() {
		    	public void onClick(DialogInterface dialog, int which) {
		    		String friendEmail = emailText.getText().toString();
		    		if (friendEmail != null && friendEmail.length() > 0) {
		    			doFriendRequest(friendEmail, DROID_ADD_ACTION, DROID_ADD_TAG);
		    		}
		    	}
	    	});
	    	
	    	friendDialogBuilder.setNegativeButton(R.string.removeFriend, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    String friendEmail = emailText.getText().toString();
                    if (friendEmail != null && friendEmail.length() > 0) {
                        doFriendRequest(friendEmail, DROID_REMOVE_ACTION, DROID_REMOVE_TAG);
                    }
                }
            });
	    	
	    	Log.d(TAG, "onCreateDialog-friend_email_dialog_id - 3");
	    	return friendDialogBuilder.create();
	    }
	    return null;
	}

    @Override
	protected Dialog onCreateDialog(int id, Bundle params) {
		switch (id) {

		 case EMAIL_DROID_DIALOG_ID:
			final Bundle parameters = params;

			LayoutInflater inflDroid = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View droidDialogLayout = inflDroid.inflate(R.layout.droid_mail_dialog,
					(ViewGroup) findViewById(R.id.root));

			AlertDialog.Builder droidDialogBuilder = new AlertDialog.Builder(this);
			droidDialogBuilder.setView(droidDialogLayout);

			final String[] droidIds = getResources().getStringArray(R.array.droid_ids);
			final Spinner spinner = (Spinner) droidDialogLayout.findViewById(R.id.spinnerDroidMail);
			ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this,
					R.array.droid_names, android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner.setAdapter(adapter);

			droidDialogBuilder.setPositiveButton(android.R.string.ok,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							int itemPos = spinner.getSelectedItemPosition();

							String action = DROID_FIND_ACTION;
							String tagResult = DROID_FIND_TAG;
							if (parameters.containsKey("action")) {
								action = parameters.getString("action");
							}
							if (parameters.containsKey("tag_result")) {
								tagResult = parameters.getString("tag_result");
							}							
							saveNickEmail();  // graba en preferencias

							SharedPreferences prefs = getSharedPreferences(
									GAME_PREFERENCES, Context.MODE_PRIVATE);
							Integer playerId = prefs.getInt(
									GAME_PREFERENCES_PLAYER_ID, -1);

							String playerEmail = prefs.getString(
									GAME_PREFERENCES_EMAIL, "");
							if (playerId == -1 || playerEmail.equals("")) { // alguno  no  establecido, no seguimos
								Toast.makeText(QuizSettingsActivity.this,
										getResources().getString(
												R.string.friend_user_not_registered),
										Toast.LENGTH_SHORT).show();
							} else {
								doFriendRequest(droidIds[itemPos], action, tagResult);
							}
							QuizSettingsActivity.this
									.removeDialog(EMAIL_DROID_DIALOG_ID);
						}
					});

			droidDialogBuilder.setNegativeButton(android.R.string.cancel,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							QuizSettingsActivity.this
									.removeDialog(EMAIL_DROID_DIALOG_ID);
						}
					});

			return droidDialogBuilder.create();
		 default:
			 return onCreateDialog(id);
		}

	}
    
	@Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "-> onPause");
        
        EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
        EditText emailText = (EditText) findViewById(R.id.EditText_Email);

        String strNickname = nicknameText.getText().toString();
        String strEmail = emailText.getText().toString();
        
        if (!((strNickname.compareTo("")==0) && (strEmail.compareTo("") == 0))) {
        	Log.d(TAG, "Save values in game preferences");
        	Editor editor = mGameSettings.edit();
            editor.putString(GAME_PREFERENCES_NICKNAME, strNickname);
            editor.putString(GAME_PREFERENCES_EMAIL, strEmail);
            editor.putBoolean(GAME_PREFERENCES_SETTINGS, false);
            editor.commit();
        }
        Log.d(TAG, "let's go to upload settings");
        Intent uploadService = new Intent(getApplicationContext(), UploaderService.class);
        startService(uploadService);
        Log.d(TAG, "upload settings ok");
    }
    
    @Override
    protected void onDestroy() {
        Log.d(TAG, "SHARED PREFERENCES");
        Log.d(TAG, "Nickname is: "  + mGameSettings.getString(GAME_PREFERENCES_NICKNAME, "Not set"));
        Log.d(TAG, "Email is: " + mGameSettings.getString(GAME_PREFERENCES_EMAIL, "Not set"));
        Log.d(TAG, "Gender (M=1, F=2, U=0) is: "  + mGameSettings.getInt(GAME_PREFERENCES_GENDER, 0));
        
        // We are not saving the password yet
        Log.d(TAG, "Password is: " + mGameSettings.getString(GAME_PREFERENCES_PASSWORD, "Not set"));
        
        // We are not saving the date of birth yet
        Log.d(TAG, "DOB is: " + DateFormat.format("MMMM dd, yyyy", 
        		mGameSettings.getLong(GAME_PREFERENCES_DOB, 0)));
        
//        Log.d(TAG, "Fav Place Name is: " + mGameSettings.getString(
//                                GAME_PREFERENCES_FAV_PLACE_NAME, "Not set"));
//        Log.d(TAG, "Fav Place GPS Lat is: " + mGameSettings.getFloat(
//                                GAME_PREFERENCES_FAV_PLACE_LAT, 0));
//        Log.d(TAG, "Fav Place GPS Lon is: " + mGameSettings.getFloat(
//                                GAME_PREFERENCES_FAV_PLACE_LONG, 0));
        
        
    	Editor editor = mGameSettings.edit();
    	editor.putBoolean(GAME_PREFERENCES_SETTINGS, false);
    	editor.commit();
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
        case TAKE_AVATAR_CAMERA_REQUEST:

            if (resultCode == Activity.RESULT_CANCELED) {
                // Avatar camera mode was canceled.
            } else if (resultCode == Activity.RESULT_OK) {

                // Took a picture, use the downsized camera image provided by
                // default
                Bitmap cameraPic = (Bitmap) data.getExtras().get("data");
                if (cameraPic != null) {
                    try {
                        saveAvatar(cameraPic);
                    } catch (Exception e) {
                        Log.e(TAG, "saveAvatar() with camera image failed.", e);
                    }
                }
            }
            break;
        case TAKE_AVATAR_GALLERY_REQUEST:

            if (resultCode == Activity.RESULT_CANCELED) {
                // Avatar gallery request mode was canceled.
            } else if (resultCode == Activity.RESULT_OK) {

                // Get image picked
                Uri photoUri = data.getData();
                if (photoUri != null) {
                    try {
                        int maxLength = 75;
                        // Full size image likely will be large. Let's scale the
                        // graphic to a more appropriate size for an avatar
                        Bitmap galleryPic = Media.getBitmap(getContentResolver(), photoUri);
                        Bitmap scaledGalleryPic = createScaledBitmapKeepingAspectRatio(
                        		galleryPic, maxLength);
                        saveAvatar(scaledGalleryPic);
                    } catch (Exception e) {
                        Log.e(TAG, "saveAvatar() with gallery picker failed.", e);
                    }
                }
            }
            break;
        case TAKE_AVATAR_SUGGEST_REQUEST:
        	Log.d(TAG, "on Activity Result suggest image");
        	if (resultCode == Activity.RESULT_CANCELED) {
        		// Gallery request mode was canceled
        	} else if (resultCode == Activity.RESULT_OK) {
        		
        		// Get image picked
                Uri photoUri = data.getData();
                if (photoUri != null) {
                    try {
                        int maxLength = 100;
                        // Full size image likely will be large. Let's scale the
                        // graphic to a more appropriate size for an avatar
                        Bitmap galleryPic = Media.getBitmap(getContentResolver(), photoUri);
                        Bitmap scaledGalleryPic = createScaledBitmapKeepingAspectRatio(
                        		galleryPic, maxLength);
                        saveImageSuggest(scaledGalleryPic);
                    } catch (Exception e) {
                        Log.e(TAG, "saveImageQuestionSuggest() with gallery picker failed.", e);
                    }
                }
        	}
        	
        	break;
        }
    }
    
    public void onLaunchCamera(View v) {
        String strAvatarPrompt = "Take your picture to store as your avatar!";
        Intent pictureIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(
                Intent.createChooser(pictureIntent, strAvatarPrompt),
                TAKE_AVATAR_CAMERA_REQUEST);
    }
    
    @Override
	protected void onPrepareDialog(int id, Dialog dialog) {
	    super.onPrepareDialog(id, dialog);
	    switch (id) {
	    case DATE_DIALOG_ID:
	        // Handle any DatePickerDialog initialization here
	        DatePickerDialog dateDialog = (DatePickerDialog) dialog;
	        int iDay, iMonth, iYear;
	        
	        // Check for date of birth preference
	        if (mGameSettings.contains(GAME_PREFERENCES_DOB)) {
	            // Retrieve Birth date setting from preferences
	            long msBirthDate = mGameSettings.getLong(GAME_PREFERENCES_DOB, 0);
	            Time dateOfBirth = new Time();
	            dateOfBirth.set(msBirthDate);
	            
	            iDay = dateOfBirth.monthDay;
	            iMonth = dateOfBirth.month;
	            iYear = dateOfBirth.year;
	        } else {
	            Calendar cal = Calendar.getInstance();
	            // Today's date fields
	            iDay = cal.get(Calendar.DAY_OF_MONTH);
	            iMonth = cal.get(Calendar.MONTH);
	            iYear = cal.get(Calendar.YEAR);
	        }
	        
	        // Set the date in the DatePicker to the date of birth OR to the current date
	        dateDialog.updateDate(iYear, iMonth, iDay);
	        
	        return;
	    case PASSWORD_DIALOG_ID:
	        // Handle any Password Dialog initialization here
	        // Since we don't want to show old password dialogs, just set new
	        // ones, we need not do anything here
	        // Because we are not "reusing" password dialogs once they have
	        // finished, but removing them from
	        // the Activity Dialog pool explicitly with removeDialog() and
	        // recreating them as needed.
	
	        return;
	    }
	}

	private void saveAvatar(Bitmap avatar) {
        String strAvatarFilename = "avatar.jpg";
        try {
            avatar.compress(CompressFormat.JPEG, 100,
                    openFileOutput(strAvatarFilename, MODE_PRIVATE));
        } catch (Exception e) {
            Log.e(TAG, "Avatar compression and save failed.", e);
        }

        Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(
                QuizSettingsActivity.this.getFilesDir(), strAvatarFilename));

        Editor editor = mGameSettings.edit();
        editor.putString(GAME_PREFERENCES_AVATAR,
                imageUriToSaveCameraImageTo.getPath());
        editor.commit();

        // Update the settings screen
        ImageButton avatarButton = (ImageButton) findViewById(R.id.ImageButton_Avatar);
        String strAvatarUri = mGameSettings
                .getString(GAME_PREFERENCES_AVATAR,
                        "android.resource://com.androidbook.btdt.hour14/drawable/avatar");
        Uri imageUri = Uri.parse(strAvatarUri);
        avatarButton.setImageURI(null); // Workaround for refreshing an
                                        // ImageButton, which tries to cache the
                                        // previous image Uri. Passing null
                                        // effectively resets it.
        avatarButton.setImageURI(imageUri);
    }
	
	private void saveImageSuggest(Bitmap image) {
		String strQuestionFilename = "question_suggested.jpg";
        
		Log.d(TAG, ">>saveImageSuggest");
		
        try {
            image.compress(CompressFormat.JPEG, 100, openFileOutput(strQuestionFilename, MODE_PRIVATE));
        } catch (Exception e) {
            Log.e(TAG, "Question compression and save failed.", e);
        }

        Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(QuizSettingsActivity.this.getFilesDir(), strQuestionFilename));

        ImageButton questionImageButton= (ImageButton) questionSuggestLayout.findViewById(R.id.ImageButton_Avatar_suggest);
        
        strSuggestImageUri = imageUriToSaveCameraImageTo.getPath();
        
        Uri imageUri = Uri.parse(strSuggestImageUri);
        
        questionImageButton.setImageURI(null);
        questionImageButton.setImageURI(imageUri);
	}
    
    /**
	 * Initialize the Avatar
	 */
	private void initAvatar() {
	    // Handle password setting dialog
	    ImageButton avatarButton = (ImageButton) findViewById(R.id.ImageButton_Avatar);
	
	    if (mGameSettings.contains(GAME_PREFERENCES_AVATAR)) {
	        String strAvatarUri = mGameSettings.getString(GAME_PREFERENCES_AVATAR,
	                        "android.resource://com.androidbook.peakbagger/drawable/avatar");
	        Uri imageUri = Uri.parse(strAvatarUri);
	        avatarButton.setImageURI(imageUri);
	    } else {
	        avatarButton.setImageResource(R.drawable.avatar);
	    }
	
	    avatarButton.setOnLongClickListener(new View.OnLongClickListener() {
	
	        public boolean onLongClick(View v) {
	            String strAvatarPrompt = "Choose a picture to use as your avatar!";
	            Intent pickPhoto = new Intent(Intent.ACTION_PICK);
	            pickPhoto.setType("image/*");
	            startActivityForResult(Intent.createChooser(pickPhoto, strAvatarPrompt),
	                    TAKE_AVATAR_GALLERY_REQUEST);
	            return true;
	        }
	    });
	
	}

	/**
	 * Initialize the Date picker
	 */
	private void initDatePicker() {
	    // Set password info
	    TextView dobInfo = (TextView) findViewById(R.id.TextView_DOB_Info);
	    if (mGameSettings.contains(GAME_PREFERENCES_DOB)) {
	        dobInfo.setText(DateFormat.format("MMMM dd, yyyy",
	        		mGameSettings.getLong(GAME_PREFERENCES_DOB, 0)));
	    } else {
	        dobInfo.setText(R.string.settings_dob_not_set);
	    }
	}

	/**
     * Initialize the email entry
     */
    private void initEmailEntry() {
        EditText emailText = (EditText) findViewById(R.id.EditText_Email);
        if (mGameSettings.contains(GAME_PREFERENCES_EMAIL)) {
            emailText.setText(mGameSettings.getString(GAME_PREFERENCES_EMAIL,
                    ""));
        }
        
        emailText.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {   

                      if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    	  Editor editor = mGameSettings.edit();
                    	  EditText emailText = (EditText) findViewById(R.id.EditText_Email);
                          editor.putString(GAME_PREFERENCES_EMAIL, emailText.getText().toString());
                          editor.commit();
                          Log.d(TAG, "Save email in preferences (Enter)");
                      }
				
				}
				return false;
			}
		});
    }

    /**
	 * Initialize the Favorite Place picker
	 */
	private void initFavoritePlacePicker() {
	    // Set place info
	    TextView placeInfo = (TextView) findViewById(R.id.TextView_FavoritePlace_Info);
	
	    if (placeInfo == null) {
	    	Log.e(TAG, "placeInfo is null");
	    }
	    
	    Log.d(TAG, "in favoritePlacePicker");
	    if (mGameSettings.contains(GAME_PREFERENCES_FAV_PLACE_NAME)) {
	    	Log.d(TAG, "ponemos uno");
	    	Log.d(TAG, "INICIANDO FAVORITE PLACE");
	        placeInfo.setText(mGameSettings.getString(GAME_PREFERENCES_FAV_PLACE_NAME, "Not set"));
	        Log.d(TAG, "puesto");
	    } else {
	    	Log.d(TAG, "favoriteplace_not_set");
	        placeInfo.setText(R.string.settings_favoriteplace_not_set);
	    }
	}

	/**
	 * Initialize the spinner
	 */
	private void initGenderSpinner() {
	    // Populate Spinner control with genders
	    final Spinner spinner = (Spinner) findViewById(R.id.Spinner_Gender);
	    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this,
	            R.array.genders, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	           
	    if (mGameSettings.contains(GAME_PREFERENCES_GENDER)) {
	        spinner.setSelection(mGameSettings.getInt(GAME_PREFERENCES_GENDER, 0));
	    }
	    
	    // Handle spinner selections
	    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
	        public void onItemSelected(AdapterView<?> parent,
	                View itemSelected, int selectedItemPosition, long selectedId) {
	            Editor editor = mGameSettings.edit();
	            editor.putInt(GAME_PREFERENCES_GENDER, selectedItemPosition);
	            editor.commit();
	            
	            String[] items = getResources().getStringArray(R.array.genders);
	            
	            if (mGameSettings.getBoolean(GAME_PREFERENCES_SETTINGS, false) == true) {
	            	String temporal = (String) getString(R.string.gender_change) + " " 
	            				+ items[mGameSettings.getInt(GAME_PREFERENCES_GENDER, 0)];
	            	//Log.i(TAG, temporal);
	            	Toast.makeText(QuizSettingsActivity.this, 
	            				temporal, Toast.LENGTH_SHORT).show();
	            } else {
	            	// Show gender toast if it changes
	                editor = mGameSettings.edit();
	            	editor.putBoolean(GAME_PREFERENCES_SETTINGS, true);
	            	editor.commit();                	
	            }
	        }
	
	        public void onNothingSelected(AdapterView<?> parent) {
	        }
	    });
	    
	}

	/**
	 * Initialize the nickname entry
	 */
	private void initNicknameEntry() {
	    EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
	    if (mGameSettings.contains(GAME_PREFERENCES_NICKNAME)) {
	        nicknameText.setText(mGameSettings.getString(
	                GAME_PREFERENCES_NICKNAME, ""));
	    }
	    
	    nicknameText.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {   
	
	                  if (keyCode == KeyEvent.KEYCODE_ENTER) {
	                	  Editor editor = mGameSettings.edit();
	                	  EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
	                      editor.putString(GAME_PREFERENCES_NICKNAME, nicknameText.getText().toString());
	                      editor.commit();
	                      Log.d(TAG, "Save nickname in preferences (Enter)");
	                  }
				
				}
				return false;
			}
		});
	}

	/**
     * Initialize the Password chooser
     */
    private void initPasswordChooser() {
        // Set password info
        TextView passwordInfo = (TextView) findViewById(R.id.TextView_Password_Info);
        if (mGameSettings.contains(GAME_PREFERENCES_PASSWORD)) {
            passwordInfo.setText(R.string.settings_pwd_set);
        } else {
            passwordInfo.setText(R.string.settings_pwd_not_set);
        }
    }

    /**
     * Called when the user presses the Favorite Location button
     * 
     * @param view
     *            The button
     */
    public void onPickPlaceButtonClick(View view) {
        showDialog(PLACE_DIALOG_ID);
    }
    
    /**
     * Called when the user presses the Set Password button
     * 
     * @param view
     *            the button
     */
    public void onSetPasswordButtonClick(View view) {
        showDialog(PASSWORD_DIALOG_ID);
    }
    
    /**
     * Called when the user presses the Set Password button
     * 
     * @param view
     *            the button
     */
    public void onSetClearButtonClick(View view) {
    	Editor editorS;
        //Clear all values from the preferences
        editorS = mGameSettings.edit();
        
        editorS.clear();
        
        if (editorS.commit()) {
        	//Clear date
        	TextView dobInfo = (TextView) findViewById(R.id.TextView_DOB_Info);
        	dobInfo.setText(R.string.settings_dob_not_set);
        	
        	//Clear nickname
        	EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
        	nicknameText.setText("");
        	
        	//Clear email
        	EditText emailText = (EditText) findViewById(R.id.EditText_Email);
        	emailText.setText("");
        	
        	//Clear password
        	TextView passwordInfo = (TextView) findViewById(R.id.TextView_Password_Info);
        	passwordInfo.setText(R.string.settings_pwd_not_set);
        } else {
        	//An error has ocurred
            Toast.makeText(QuizSettingsActivity.this,
                    "Error cleaning the changes", Toast.LENGTH_LONG).show();
        }
        
        if (mGameSettings.contains(GAME_PREFERENCES_NICKNAME)){
        	Log.d(TAG, "Existe name");
        }
        if (mGameSettings.contains(GAME_PREFERENCES_EMAIL)){
        	Log.d(TAG, "Existe email");
        }
        if (mGameSettings.contains(GAME_PREFERENCES_GENDER)){
        	Log.d(TAG, "Existe gender");
        }
        if (mGameSettings.contains(GAME_PREFERENCES_PASSWORD)){
        	Log.d(TAG, "Existe password");
        }
        if (mGameSettings.contains(GAME_PREFERENCES_SCORE)){
        	Log.d(TAG, "Existe score");
        }
        if (mGameSettings.contains(GAME_PREFERENCES_CURRENT_QUESTION)){
        	Log.d(TAG, "Existe current question");
        }
        if (mGameSettings.contains(GAME_PREFERENCES_DOB)){
        	Log.d(TAG, "Existe dob");
        }
    }

    /**
     * Called when the user presses the Pick Date button
     * @param view
     *            The button
     */
    public void onPickDateButtonClick(View view) {
    	showDialog(DATE_DIALOG_ID);
    }
    
    /**
     * Scale a Bitmap, keeping its aspect ratio
     * 
     * @param bitmap
     *            Bitmap to scale
     * @param maxSide
     *            Maximum length of either side
     * @return a new, scaled Bitmap
     */
    private Bitmap createScaledBitmapKeepingAspectRatio(Bitmap bitmap,
            int maxSide) {
        int orgHeight = bitmap.getHeight();
        int orgWidth = bitmap.getWidth();

        // scale to no longer any either side than 75px
        int scaledWidth = (orgWidth >= orgHeight) ? maxSide
                : (int) ((float) maxSide * ((float) orgWidth / (float) orgHeight));
        int scaledHeight = (orgHeight >= orgWidth) ? maxSide
                : (int) ((float) maxSide * ((float) orgHeight / (float) orgWidth));

        // create the scaled bitmap
        Bitmap scaledGalleryPic = Bitmap.createScaledBitmap(bitmap,
                scaledWidth, scaledHeight, true);
        return scaledGalleryPic;
    }
    
    /**
     * 
     * If location name can't be determined, try to determine location based on current coords
     * 
     * @param strLocation
     *            Location or place name to try
     */
    private void resolveLocation(String strLocation) {
        boolean bResolvedAddress = false;

        if (strLocation.equalsIgnoreCase(getResources().getString(R.string.settings_favplace_currentlocation)) == false) {
            bResolvedAddress = lookupLocationByName(strLocation);
        }

        if (bResolvedAddress == false) {
            // If String place name could not be determined (or matches the string for "current location", assume this is a custom name of the current location
            calculateCurrentCoordinates();
        }
    }

    /**
     * Helper to format coordinates for screen display
     * 
     * @param lat
     * @param lon
     * @return A string formatted accordingly
     */
    private String formatCoordinates(float lat, float lon) {
        StringBuilder strCoords = new StringBuilder();
        strCoords.append(lat).append(",").append(lon);
        return strCoords.toString();
    }
    
    /**
     * Attempt to get the last known location of the device. Usually this is
     * the last value that a location provider set
     */
    private void calculateCurrentCoordinates() {
        float lat = 0, lon = 0;

        try {
            LocationManager locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
            Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            lat = (float) recentLoc.getLatitude();
            lon = (float) recentLoc.getLongitude();
        } catch (Exception e) {
            Log.e(TAG, "Location failed", e);
        }

        GPSCoords temp = new GPSCoords(lat, lon, "");
        mFavPlaceCoords.add(temp);
    }

    /**
     * 
     * Take a description of a location, store the coordinates in mFavPlaceCoords
     * 
     * @param strLocation
     *            The location or placename to look up
     * @return true if the address or place was recognized, otherwise false
     */
    private boolean lookupLocationByName(String strLocation) {
        // Cambiamos a GeocoderEmul en emulador con API >= 2.2
//        final Geocoder coder = new Geocoder(getApplicationContext());
        final GeocoderEmul coder = new GeocoderEmul();
        boolean bResolvedAddress = false;
        Log.d(TAG, "I'm in lookupLocationByName");

        try {
        	mFavPlaceCoords = new ArrayList<GPSCoords>();
        	
        	
        	// Number of results 3
            List<Address> geocodeResults = coder.getFromLocationName(strLocation, 3);
            Iterator<Address> locations = geocodeResults.iterator();

            // Fill the spinner
            Spinner spinLocations = (Spinner) dialogLayout.findViewById(R.id.spinner_Place);
            List<String> items = new ArrayList<String>();
            ArrayAdapter <String> adapter = new ArrayAdapter <String> (this, android.R.layout.simple_spinner_item, items);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            
            String temporalString = "";
            
            Log.d(TAG, "fill the spinner");
            while (locations.hasNext()) {
            	temporalString = "";
            	Log.d(TAG, "<<<<< get the locations >>>>>");
                Address loc = locations.next();
                String via_publica = loc.getThoroughfare();
                if (via_publica == null) {
                	Log.d(TAG, "Via publica null");
                } else {
                	temporalString = temporalString + via_publica + ", ";
                	Log.d(TAG, "Via publica = " + via_publica + (">>> ") + temporalString);
                }
                
                String localidad = loc.getLocality();
                if (localidad == null) {
                	Log.d(TAG, "Localidad null");
                } else {
                	temporalString = temporalString + localidad;
                	Log.d(TAG, "Localidad = " + localidad + (">>> ") + temporalString);
                }
                
                if (localidad == null && via_publica == null) {
                	adapter.add("Unknow");
                } else {
                	Log.d(TAG, "temporalString = " + temporalString);
                	adapter.add(temporalString);
                }
                
                //Create a new GPSCoords object
                GPSCoords coordsTemp;
                coordsTemp = new GPSCoords((float) loc.getLatitude(), (float) loc.getLongitude(), temporalString);
                
                //Add GPSCoords object to the list
                mFavPlaceCoords.add(coordsTemp);
                
                selectItem = 0;
                bResolvedAddress = true;
            }
            
            if (spinLocations == null) {
            	Log.d(TAG, "spin is null");
            } else {
            	spinLocations.setAdapter(adapter);
            }
            Log.d(TAG, "Locations end");
        } catch (Exception e) {
            Log.e(TAG, "Failed to geocode location", e);
        }
        return bResolvedAddress;
    }

    private void saveNickEmail(){ 
		EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
		EditText emailText = (EditText) findViewById(R.id.EditText_Email);

		String strNickname = nicknameText.getText().toString();
		String strEmail = emailText.getText().toString();

		Editor editor = mGameSettings.edit();
		editor.putString(GAME_PREFERENCES_NICKNAME, strNickname);
		editor.putString(GAME_PREFERENCES_EMAIL, strEmail);

		editor.commit();
	}
    
    private class GPSCoords {
        float mLat;
        float mLon;
        String name_place;

        GPSCoords(float lat, float lon, String name) {
            mLat = lat;
            mLon = lon;
            name_place = name;
        }
    }
    
    private class FriendRequestTask extends AsyncTask<String, Object, Boolean> {
		@Override
		protected void onPostExecute(Boolean result) {
				QuizSettingsActivity.this.setProgressBarIndeterminateVisibility(false);
				String toastText;
				if(!result) { //Invite a friend
					AlertDialog alertDialog = new AlertDialog.Builder(QuizSettingsActivity.this).create();
					alertDialog.setTitle(getResources().getString(R.string.inviteTitle));
					alertDialog.setMessage(getResources().getString(R.string.inviteText));
					alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
							emailIntent.setType("plain/text");

							emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "You have been invited" +
									" to install BTDT now and enjoy!");

							emailIntent.setType("plain/text");
							emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "You have been invited" +
									"to install BTDT. Enjoy whith this fantastic game. Do it now!");

							startActivity(Intent.createChooser(emailIntent, "Send your email in:"));
							
						}
					});
					
					alertDialog.setButton2("Not now", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							/* Nothing to do. Only exit the alertDialog. */							
						}
					});
					
					alertDialog.show();
				}
				else {
					toastText = getResources().getString(R.string.friend_operation_succeeded);
					Toast.makeText(QuizSettingsActivity.this, toastText, Toast.LENGTH_SHORT).show();
				}
		}

		@Override
		protected void onPreExecute() {
			QuizSettingsActivity.this.setProgressBarIndeterminateVisibility(true);
		}

		@Override
		protected Boolean doInBackground(String... params) {
			Boolean succeeded = false;
			Boolean droidFriend = false;
			Log.d(TAG, "doInBackground> FriendRequestTask");
			try {
				String friendEmail = params[0];
				String action = params[1];
				String tagResult = params[2];
				Log.d(TAG, "doInBackground> frienEmail:" + friendEmail + " -action:" + action + " -tagResult:" + tagResult);
				int droidId;
				
				try {
					droidId = Integer.parseInt(friendEmail);//truco
				} catch (NumberFormatException e) {
					droidId = -1;
				}
				
				if(droidId != -1) { // si friendEmail es numerico
					droidFriend = true;
				}
				SharedPreferences prefs = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
				Integer playerId = prefs.getInt(GAME_PREFERENCES_PLAYER_ID, -1);                

				if(droidFriend == true) {
					Log.d(TAG, "doInBackground> droidFriend is true");
					String playerEmail = prefs.getString(GAME_PREFERENCES_EMAIL, "");
					if(playerId == -1 || playerEmail.equals("")) { // alguno no establecido
						return succeeded;// no seguimos
					}

					playerId = droidId; // cambiamos de jugador
					friendEmail = playerEmail; // cambiamos de amigo
				}
				
				Vector<NameValuePair> vars = new Vector<NameValuePair>();
				// vars.add(new BasicNameValuePair("command", "add"));
				vars.add(new BasicNameValuePair("command", action));
				vars.add(new BasicNameValuePair("playerId", playerId.toString()));
				vars.add(new BasicNameValuePair("friend", friendEmail));

				HttpClient client = new DefaultHttpClient();

				// an example of using HttpClient with HTTP POST and form variables
				HttpPost request = new HttpPost(TRIVIA_SERVER_FRIEND_ADD);
				request.setEntity(new UrlEncodedFormEntity(vars));

				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String responseBody = client.execute(request, responseHandler);

				Log.d(TAG, "doInBackground> " + action + " friend result: " + responseBody);
				// if (responseBody != null) {
				if (responseBody.contains(tagResult + "true")) {
					succeeded = true;
				}
			} catch (MalformedURLException e) {
				Log.e(TAG, "Failed to add friend", e);
			} catch (IOException e) {
				Log.e(TAG, "Failed to add friend", e);
			}

			return succeeded;
		}
    }
    
    
	public static class UploaderService extends Service {
		private static final String DEBUG_TAG = "QuizSettingsActivity$UploaderService";
		private UploadTask uploader;
		
		@Override
		public int onStartCommand(Intent intent, int flags, int startId) {
			Log.d(TAG, "onStartCommand - UploaderService");
			
			if (intent.getAction() != null && intent.getAction().equals(SUGGEST_SERVICE)) {
				Log.d(TAG, "UploaderService-onStartCommand-Suggest Service");
				Bundle bundle = intent.getExtras();
				String pImageUri = bundle.getString("imageUri");
				String pQuestion = bundle.getString("question");
				if (pImageUri == null || pQuestion == null) {
					return -1; //error
				}
				uploader = new UploadTask(true, bundle);				
				uploader.execute();
				
				Log.d(DEBUG_TAG, "Upload suggest requested");
			} else { //Upload settings
				Log.d(TAG, "UploaderService-onStartCommand-Normal");
				uploader = new UploadTask();
				uploader.execute();
				
				Log.d(DEBUG_TAG, "Settings and image upload requested");
			}
			return START_REDELIVER_INTENT;
		}
		
		@Override
		public IBinder onBind(Intent intent) {
			// no binding
			return null;
		}
		
		private class UploadTask extends AsyncTask<Object, String, Boolean> {
			SharedPreferences mGameSettings;
			boolean suggestUpload;
			Bundle bundleSuggest;
			
			public UploadTask() {
				suggestUpload = false;
				bundleSuggest = null;
			}
			
			public UploadTask(boolean suggest, Bundle b) {
				suggestUpload = suggest;
				bundleSuggest = b;
			}
			
			@Override
			protected void onPostExecute(Boolean result) {
				if (result) {
					//Toast.makeText(QuizActivity.this,"Question correctly upload", Toast.LENGTH_LONG).show();
				} else {
					Log.d(TAG, "pregunta sugerida no subida correctamente");
					//Toast.makeText(QuizActivity.this,"An error ocurred during the upload", Toast.LENGTH_LONG).show();
				}
			}
		 
			@Override
			protected void onPreExecute() {
				mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
			}
		
			@Override
			protected Boolean doInBackground(Object... params) {
				boolean result;
				if (suggestUpload) {
					result = postSuggestionToServer();
					if (getApplicationContext() == null) {
						Log.d(TAG, "context is null");
					} else {
						Log.d(TAG, "context is not null");
					}
					if (result) {
						Log.d(TAG, "pregunta sugerida subida correctamente");
						//Toast.makeText(cxt.getApplicationContext(),"Question correctly upload", Toast.LENGTH_LONG).show();
					} else {
						Log.d(TAG, "pregunta sugerida no subida correctamente");
						//Toast.makeText(cxt.getApplicationContext(),"An error ocurred during the upload", Toast.LENGTH_LONG).show();
					}
					
				} else {
					result = postSettingsToServer();
					if (result && !isCancelled()) {
						result = postAvatarToServer();
					}
					Log.d(DEBUG_TAG, "Done uploading settings and image");
				}
				return result;
			}
			
			private boolean postSuggestionToServer() {
				boolean succeeded = false;
				String questionText = bundleSuggest.getString("question");
				String imageUriText = bundleSuggest.getString("imageUri");
				Integer playerId = mGameSettings.getInt(GAME_PREFERENCES_PLAYER_ID, -1);
				
				MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
				File file = new File(imageUriText);
				
				if (file.exists()) {
					try {
						FileBody encFile = new FileBody(file);
						entity.addPart("questionImage", encFile);
						entity.addPart("questionText", new StringBody(questionText.toString()));
						entity.addPart("playerId", new StringBody(playerId.toString()));
		
						HttpPost request = new HttpPost(TRIVIA_SERVER_SUGGEST);
						request.setEntity(entity);
						
						HttpClient client = new DefaultHttpClient();
	
						ResponseHandler<String> responseHandler = new BasicResponseHandler();
						String responseBody = client.execute(request, responseHandler);
	
						if (responseBody != null && responseBody.length() > 0) {
							Log.w(DEBUG_TAG, "Unexpected response from suggest upload: " + responseBody);
						}
						
						Log.d(TAG, "Subido correctamente");
						if (responseBody != null && responseBody.contains("false")) {
							succeeded = false;
						}
						if (responseBody == null) {
							succeeded = false;
						}
						if (responseBody != null && responseBody.contains("true")) {
							succeeded = true;
						}
					} catch (ClientProtocolException e) {
						Log.e(DEBUG_TAG, "Unexpected ClientProtocolException", e);
					} catch (IOException e) {
						Log.e(DEBUG_TAG, "Unexpected IOException", e);
					}
				} else {
					Log.d(DEBUG_TAG, "No image to upload");
					succeeded = false;
				}
				
				return succeeded;
			}
		 
			private boolean postSettingsToServer() {
				boolean succeeded = false;
				// an example of using HttpClient with HTTP GET and form variables
				String uniqueId = mGameSettings.getString(GAME_PREFERENCES_UNIQUE_ID, null);
				Integer playerId = mGameSettings.getInt(GAME_PREFERENCES_PLAYER_ID, -1);
				String nickname = mGameSettings.getString(GAME_PREFERENCES_NICKNAME, "");
				String email = mGameSettings.getString(GAME_PREFERENCES_EMAIL,"");
				String password = mGameSettings.getString(GAME_PREFERENCES_PASSWORD, "");
				Integer score = mGameSettings.getInt(GAME_PREFERENCES_SCORE, -1);
				Integer gender = mGameSettings.getInt(GAME_PREFERENCES_GENDER,-1);
				Long birthdate = mGameSettings.getLong(GAME_PREFERENCES_DOB, 0);
				String favePlaceName = mGameSettings.getString(GAME_PREFERENCES_FAV_PLACE_NAME, "");
				Vector<NameValuePair> vars = new Vector<NameValuePair>();
				
				if (uniqueId == null) {
					// If we don't have a unique id yet, create one and save it
					uniqueId = UUID.randomUUID().toString();
					Log.d(DEBUG_TAG, "Unique ID: " + uniqueId);
					
					// why not use getDeviceId from TelephonyManager?
					// See: http://goo.gl/sAbV2
					// In short, it only works on phones. Got a wifi only
					// tablet? A TV? forget it.
	
					// save it in the prefs
					Editor editor = mGameSettings.edit();
					editor.putString(GAME_PREFERENCES_UNIQUE_ID, uniqueId);
					editor.commit();
				}
		
				// add the uniqueId to the request
				vars.add(new BasicNameValuePair("uniqueId", uniqueId));
		
				if (playerId != -1) {
					// otherwise, we use the playerId to update data
					vars.add(new BasicNameValuePair("updateId", playerId.toString()));
		
					// and we go ahead and push up the latest score
					vars.add(new BasicNameValuePair("score", score.toString()));
				}
		
				vars.add(new BasicNameValuePair("nickname", nickname));
				vars.add(new BasicNameValuePair("email", email));
				vars.add(new BasicNameValuePair("password", password));
				vars.add(new BasicNameValuePair("gender", gender.toString()));
				vars.add(new BasicNameValuePair("faveplace", favePlaceName));
				vars.add(new BasicNameValuePair("dob", birthdate.toString()));
		
				String url = TRIVIA_SERVER_ACCOUNT_EDIT + "?" + URLEncodedUtils.format(vars, null);
				HttpGet request = new HttpGet(url);
		
				try {
					ResponseHandler<String> responseHandler = new BasicResponseHandler();
					HttpClient client = new DefaultHttpClient();
					String responseBody = client.execute(request,responseHandler);
	
					if (responseBody != null && responseBody.length() > 0) {
						Integer resultId = Integer.parseInt(responseBody);
						Editor editor = mGameSettings.edit();
						editor.putInt(GAME_PREFERENCES_PLAYER_ID, resultId);
						editor.commit();
					}
					succeeded = true;
				} catch (ClientProtocolException e) {
					Log.e(DEBUG_TAG, "Failed to get playerId (protocol): ", e);
				} catch (IOException e) {
					Log.e(DEBUG_TAG, "Failed to get playerId (io): ", e);
				}
				
				return succeeded;
			}
		
			private boolean postAvatarToServer() {
				boolean succeeded = false;
				
				// an example using HttpClient and HttpMime to upload a file via
				// HTTP POST in the same
				// way a web browser might, using multipart MIME encoding
				String avatar = mGameSettings.getString(GAME_PREFERENCES_AVATAR, "");
				Integer playerId = mGameSettings.getInt(GAME_PREFERENCES_PLAYER_ID, -1);
				
				MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
				File file = new File(avatar);
	
				if (file.exists()) {
					FileBody encFile = new FileBody(file);
					entity.addPart("avatar", encFile);
					
					try {
						entity.addPart("updateId",new StringBody(playerId.toString()));
					} catch (UnsupportedEncodingException e) {
						Log.e(DEBUG_TAG, "Failed to add form field.", e);
					}
	
					HttpPost request = new HttpPost(TRIVIA_SERVER_ACCOUNT_EDIT);
					request.setEntity(entity);
					
					HttpClient client = new DefaultHttpClient();
	
					try {
						ResponseHandler<String> responseHandler = new BasicResponseHandler();
						String responseBody = client.execute(request, responseHandler);
	
						if (responseBody != null && responseBody.length() > 0) {
							Log.w(DEBUG_TAG, "Unexpected response from avatar upload: " + responseBody);
						}
						
						succeeded = true;
					} catch (ClientProtocolException e) {
						Log.e(DEBUG_TAG, "Unexpected ClientProtocolException", e);
					} catch (IOException e) {
						Log.e(DEBUG_TAG, "Unexpected IOException", e);
					}
				} else {
					Log.d(DEBUG_TAG, "No avatar to upload");
					succeeded = true;
				}
	
				return succeeded;
			}
		}
	}
}
  
	